<template>
    <div class="view-tool-json-formatter">
        <el-row :gutter="20">
            <el-col :span="12">
                <div style="display: flex;justify-content: space-between;margin-bottom: 10px;">
                    <span class="title">原始数据</span>
                    <span>
                        <el-button size="small" type="primary" @click="format">格式化</el-button>
                        <el-button size="small" type="primary" @click="compress">压缩</el-button>
                    </span>
                </div>
                <el-input type="textarea" :rows="10" v-model="original" placeholder="" :maxlength="-1"
                    :show-word-limit="false">
                </el-input>
            </el-col>
            <el-col :span="12">
                <div style="display: flex;justify-content: space-between;margin-bottom: 10px;">
                    <span class="title">输出：</span>
                    <span>
                        <el-button size="small" type="primary" icon="CopyDocument" @click="copy">Copy</el-button>
                    </span>
                </div>
                <el-input type="textarea" readonly :rows="10" v-model="formatted" placeholder="" :maxlength="-1"
                    :show-word-limit="false">
                </el-input>
            </el-col>
        </el-row>
    </div>
</template>
<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
const original = ref('')
const formatted = ref('')

const format = () => {
    try {
        const json = JSON.parse(original.value)
        formatted.value = JSON.stringify(json, null, 2)
    } catch (error) {
        console.error(error)
        formatted.value = error.message
    }
}

// 压缩
const compress = () => {
    try {
        const json = JSON.parse(original.value)
        formatted.value = JSON.stringify(json)
    } catch (error) {
        console.error(error)
        formatted.value = error.message
    }
}

const copy = () => {
    navigator.clipboard.writeText(formatted.value)
    ElMessage.success('复制成功')
}
</script>